package cn.shopping.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.shopping.common.utils.PageUtils;
import cn.shopping.common.utils.Query;

import cn.shopping.product.dao.CategoryDao;
import cn.shopping.product.entity.CategoryEntity;
import cn.shopping.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询出所有的类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        //封装称为树形结构
        //找到所有的parent_id=0的分类
        List<CategoryEntity> categoryEntity=categoryEntityList.stream()
                .filter(categoryEntity1 -> categoryEntity1.getParentCid()==0)
                .peek(categoryEntity1 -> categoryEntity1.setChildCategory(getChileCategoryList(categoryEntity1,categoryEntityList)))
                .sorted((category1,category2)->category1.getSort()==null?0:category1.getSort()-(category2.getSort()==null?0:category2.getSort()))
                .collect(Collectors.toList());
        return categoryEntity;
    }

    private List<CategoryEntity> getChileCategoryList(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity>  categoryEntityList =all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildCategory(getChileCategoryList(categoryEntity,all)))
                .sorted((category1,category2)->category1.getSort()==null?0:category1.getSort()-(category2.getSort()==null?0:category2.getSort()))
                .collect(Collectors.toList());
        return  categoryEntityList.isEmpty()?null:categoryEntityList;
    }

}